package gw.com.android.presenter;

import com.gwtsz.gts2.hx.R;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.Locale;

import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.DoubleConverter;
import www.com.library.util.JsonUtil;

/**
 * Created by reeta.zou on 2017/3/15.
 * 下单界面数据处理逻辑
 */

public class TradePresenter extends BasePresenter {
    private int mUiCode;
    public DataItemResult mMarginList;
    private DataItemResult mPositionList;
    public boolean isMargin = false;
    public boolean isCNY = false;
    public double rate = 0;
    public int rateDigit = 0;

    public TradePresenter(int code) {
        mUiCode = code;
        mMarginList = new DataItemResult();
        isCNY = DataManager.instance().isCNY();
        setMarginLevel(code);
    }

    /**
     * 层级保证金数据获取
     */
    public void setMarginLevel(int code) {
        mUiCode = code;
        isMargin = DataManager.instance().hasMargin();
        if (isMargin && GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_GUEST) {
            String jsonStr2 = AppTerminal.instance().getMarginLevel(mUiCode);
            Logger.e("jsonStr2 == " + jsonStr2);
            try {
                if (JsonUtil.isJsonData(jsonStr2)) {
                    JSONArray mArray2 = new JSONArray(jsonStr2);
                    mMarginList.clear();
                    JsonUtil.toDataItemResult(mMarginList, mArray2);
                } else {
                    mMarginList.clear();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            mMarginList.clear();
        }
    }

    /**
     * 层级保证金的计算逻辑
     */
    public String calLevelMargin(double newLot, float marginInit, int mTradeDir) {
        return calLevelMargin(newLot, marginInit, mTradeDir, false);
    }

    /**
     * @param prefix$ 返回金额前加 $ 符号
     */
    public String calLevelMargin(double newLot, float marginInit, int mTradeDir, boolean prefix$) {
        DataItemDetail item = DataManager.instance().getTickModel(GTSConst.CNY_CODE);
        if (null != item) {
            rateDigit = item.getInt(GTSConst.JSON_KEY_DIGITS);
            rate = DoubleConverter.toDouble(rateDigit, DoubleConverter.toDoubleData(item.getString(GTSConst.JSON_KEY_CURPRICE)));
        }
        Logger.e("保证金 rate == " + rate + ", rateDigit =" + rateDigit);
        if (!isMargin) {
            return calMargin(newLot, marginInit, prefix$);
        } else if (mMarginList.getDataCount() < 1) {
            return calMargin(newLot, 0, prefix$);
        }
        mPositionList = DataManager.instance().getPositionByCodeId(mUiCode);
        double margin = 0;
        double lot = 0;
        if (mTradeDir == AppContances.TRADE_TYPE_SALE) {
            lot = DoubleConverter.toFloatData(mPositionList.detailInfo.getString(GTSConst.JSON_KEY_POSITION_TOTAL_SELL_LOTS));
        } else {
            lot = DoubleConverter.toFloatData(mPositionList.detailInfo.getString(GTSConst.JSON_KEY_POSITION_TOTAL_BUY_LOTS));
        }
        newLot = DoubleConverter.toDoubleData(DoubleConverter.to2Decimal(newLot));
        lot = DoubleConverter.toDoubleData(DoubleConverter.to2Decimal(lot));
        if (isCNY) {
            margin = getItemLevelLockMoneyCNY(lot, newLot, mTradeDir, rate);
            Logger.e("保证金人民币最终结果 getItemLevelLockMoneyCNY MarginInitial == " + margin);
            return DoubleConverter.toStringData(margin + 0.0001, 2) + AppMain.getAppString(R.string.CNH);
        } else {
            margin = getItemLevelLockMoney(lot, newLot);
            Logger.e("保证金美元最终结果 getItemLevelLockMoney MarginInitial == " + margin);
            if (prefix$) {
                return "$" + DoubleConverter.toStringData(margin + 0.0001, 2);
            } else {
                return DoubleConverter.toStringData(margin + 0.0001, 2) + AppMain.getAppString(R.string.USD);
            }
        }
    }


    /**
     * 根据手数计算保证金
     */
    private String calMargin(double lot, float marginInit, boolean prefix$) {
        double margin = 0;
        margin = lot * marginInit;
        if (isCNY) {
            return AppMain.getAppString(R.string.order_title_CNY, margin * rate);
        }
        if (prefix$) {
            return String.format(Locale.getDefault(), "$%1$.2f", margin);
        } else {
            return AppMain.getAppString(R.string.order_title_USD, margin);
        }
    }

    /**
     * 计算单笔所需参考保证金,(美元账户)
     *
     * @param lot    当前持仓列表同方向已持仓手数
     * @param newLot 当前要下的手数
     * @return
     */
    private double getItemLevelLockMoney(double lot, double newLot) {
        return getLevelLockMoney(lot + newLot) - getLevelLockMoney(lot);
    }

    /**
     * 计算单笔所需参考保证金(人民币）
     *
     * @param lot    当前持仓列表同方向已持仓手数
     * @param newLot 当前要下的手数
     * @return
     */
    private double getItemLevelLockMoneyCNY(double lot, double newLot, int mTradeDir, double exchange_rate) {
        return getLevelLockMoney(lot + newLot) * getItemLevelOpenRate(lot, newLot, mTradeDir, exchange_rate) - getLevelLockMoney(lot) * getItemLevelOpenRateByTradeDir(lot, mTradeDir);
    }

    /**
     * 计算需要的汇率(总加权汇率)
     *
     * @param lot 当前持仓列表同方向已持仓手数
     * @return
     */
    private double getItemLevelOpenRate(double lot, double newLot, int mTradeDir, double exchange_rate) {
        double OpenRate = 0;
        double totalLot = lot + newLot;
        if (totalLot != 0) {
            OpenRate = (getPositionMarginRate(mTradeDir) + exchange_rate * newLot) / totalLot;
        }
        if (DoubleConverter.isEqual(lot, 0, 2)) {
            OpenRate = DoubleConverter.toDouble(rateDigit, OpenRate);
        }
        Logger.e("保证金加权汇率 getItemLevelOpenRate OpenRate == " + OpenRate);
        return OpenRate;
    }

    /**
     * 计算需要的汇率(持仓单方向上的加权汇率)
     *
     * @param mTradeDir 当前方向
     * @return
     */
    private double getItemLevelOpenRateByTradeDir(double lot, int mTradeDir) {
        double OpenRate = 0;
        if (lot != 0) {
            OpenRate = getPositionMarginRate(mTradeDir) / lot;
        }
//        OpenRate = DoubleConverter.toDouble(rateDigit, OpenRate);
        Logger.e("保证金持仓单加权汇率 getItemLevelOpenRateByTradeDir OpenRate == " + OpenRate);
        return OpenRate;

    }

    /**
     * 根据持仓name，返回该产品买卖方向加权汇率
     *
     * @return
     */
    private double getPositionMarginRate(int tradeType) {
        double totalMarginRate = 0;
        if (mPositionList.getDataCount() > 0) {
            for (int i = 0; i < mPositionList.getDataCount(); i++) {
                DataItemDetail mPositionInfo = mPositionList.getItem(i);
                if (tradeType == AppContances.TRADE_TYPE_SALE) {
                    if (null != mPositionInfo && mPositionInfo.getInt(GTSConst.JSON_KEY_DIRECTION) == AppContances.TRADE_TYPE_SALE) {
                        totalMarginRate = (DoubleConverter.toDoubleData(mPositionInfo.getString(GTSConst.JSON_KEY_OPENMARGINRATE))
                                * DoubleConverter.toDoubleData(mPositionInfo.getString(GTSConst.JSON_KEY_VOLUME))) + totalMarginRate;
                    }
                } else {
                    if (null != mPositionInfo && mPositionInfo.getInt(GTSConst.JSON_KEY_DIRECTION) == AppContances.TRADE_TYPE_BUY) {
                        totalMarginRate = (DoubleConverter.toDoubleData(mPositionInfo.getString(GTSConst.JSON_KEY_OPENMARGINRATE))
                                * DoubleConverter.toDoubleData(mPositionInfo.getString(GTSConst.JSON_KEY_VOLUME))) + totalMarginRate;
                    }
                }

            }
            return totalMarginRate;
        }
        return totalMarginRate;
    }

    /**
     * 根据手数返回对应的层级保证金(参考保证金)
     * lot 手数
     * marginLevelList 计算产品的层级数据
     */
    public double getLevelLockMoney(double lot) {
        DataItemDetail marginModel;
        int level = 1;//当前手数在哪一层
        for (int i = 0; i < mMarginList.getDataCount(); i++) {
            if (lot > DoubleConverter.toDoubleData(mMarginList.getItem(i).getString(GTSConst.JSON_KEY_VOLUMESMAX))) {
                level++;
            }
        }
        level = level > mMarginList.getDataCount() ? mMarginList.getDataCount() : level;
        double levelLockMoney = 0;
        for (int i = 0; i < level; i++) {
            marginModel = mMarginList.getItem(i);
            if (i == 0) {
                if (level == 1) {
                    levelLockMoney += lot * DoubleConverter.toDoubleData(marginModel.getString(GTSConst.JSON_KEY_MARGININITIAL));
                } else {
                    levelLockMoney += DoubleConverter.toDoubleData(marginModel.getString(GTSConst.JSON_KEY_VOLUMESMAX))
                            * DoubleConverter.toDoubleData(marginModel.getString(GTSConst.JSON_KEY_MARGININITIAL));
                }
            } else if (i >= level - 1) {
                levelLockMoney += (Math.abs(lot - DoubleConverter.toDoubleData(mMarginList.getItem(i - 1).getString(GTSConst.JSON_KEY_VOLUMESMAX))))
                        * DoubleConverter.toDoubleData(marginModel.getString(GTSConst.JSON_KEY_MARGININITIAL));

            } else {
                levelLockMoney += (DoubleConverter.toDoubleData(marginModel.getString(GTSConst.JSON_KEY_VOLUMESMAX))
                        - DoubleConverter.toDoubleData(mMarginList.getItem(i - 1).getString(GTSConst.JSON_KEY_VOLUMESMAX)))
                        * DoubleConverter.toDoubleData(marginModel.getString(GTSConst.JSON_KEY_MARGININITIAL));

            }

        }
        Logger.e("保证金层级计算结果 MarginInitial == " + levelLockMoney);
        return levelLockMoney;
    }

}
